package cn.lee.cplibrary.util.uni;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.view.Gravity;

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.lee.cplibrary.util.LogUtil;
import cn.lee.cplibrary.widget.dialog.CpComDialog;
import cn.lee.cplibrary.util.permissionutil.PermissionProxy;
import cn.lee.cplibrary.util.permissionutil.PermissionUtil;
import cn.lee.cplibrary.util.system.AppUtils;
import cn.lee.cplibrary.util.timer.TimeUtils;

/**
 * 首页Uni权限权利
 * create by ChrisLee on 2021/10/19
 */
public class UniPersUtil {
    protected Activity activity;
    protected Fragment fragment;
    protected PermissionUtil permissionUtil;
    protected String guideDialogMsg = "缺少权限会导致APP部分功能不可用。请点击\"设置\"-\"权限\"-打开所需权限";
    protected boolean isShowGuideDialog = true;//用户永久拒绝需要的权限时，是否显示引导对话框，使用时候可自行设置
    protected boolean isHandleResult = true;//是否处理申请结果
    protected  GrantedCallBack callBack;
    /**
     * 在Activity中使用
     */
    public UniPersUtil(Activity activity) {
        this.activity = activity;
        permissionUtil = new PermissionUtil(proxy);
    }

    /**
     * 在Fragment中使用
     */
    public UniPersUtil(Fragment fragment) {
        this.fragment = fragment;
        this.activity = fragment.getActivity();
        permissionUtil = new PermissionUtil(proxy);

    }

    /**
     * 申请权限
     * 注意顺序：先setCallBack 再 requestPermissions
     */
    public void requestPermissions(String[] pers, int requestCode) {
        if (fragment == null) {
            permissionUtil.requestPermissions(activity, requestCode, pers);
        } else {
            permissionUtil.requestPermissions(fragment, requestCode, pers);
        }
    }

    /**
     * （必须调用本方法）
     * 权限申请结果处理,在Activity或者Fragment的onRequestPermissionsResult方法中的super方法上一行调用
     * eg：
     */
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (isHandleResult) {
            if (fragment == null) {
                permissionUtil.onRequestPermissionsResult(activity, requestCode, permissions, grantResults);
            } else {
                permissionUtil.onRequestPermissionsResult(fragment, requestCode, permissions, grantResults);
            }
        }

    }

    private PermissionProxy proxy = new PermissionProxy() {
        @Override
        public void granted(Object source, int requestCode) {
            if (callBack != null) {
                LogUtil.i("", "requestCode=" + requestCode+"---source="+source);
                callBack.granted(source, requestCode);
            }
        }

        @Override
        public void denied(Object source, int requestCode, List deniedPermissions) {
            LogUtil.i("", "denied=" + deniedPermissions);
            Map<String, List<String>> map = groupDeniedPermissions(activity, deniedPermissions);
            List<String> list = map.get("show");
            if (list.size() > 0) {//尚有未允许的权限，且允许弹框的，后面不执行deniedNoShow，
                if (callBack != null) {
                    callBack.needCheck(list);
                }
            }
        }

        @Override
        public void deniedNoShow(Object source, int requestCode, List noShowPermissions) {
            LogUtil.i("", "deniedNoShow=" + noShowPermissions);
//            showGuideDialog(activity,noShowPermissions);
            if (callBack != null) {
                callBack.deniedNoShow(noShowPermissions);
            }
        }

        @Override
        public void rationale(Object source, int requestCode) {

        }

        @Override
        public boolean needShowRationale(int requestCode) {
            return false;
        }
    };

    public void showGuideDialog(final Activity c, List noShowPermissions) {
        TimeUtils.isCheckFastClick = false;
        CpComDialog.Builder.builder(c).
                setTitle("提示").setContent(guideDialogMsg).setTxtCancel("拒绝").setSure("开启")
                .setTitleSize(20).setContentSize(16).setBtnSize(20)
                .setBtnCancelColor(Color.parseColor("#8d8d8d"))
                .setGravity(Gravity.LEFT)
                .setCancel(false)
                .build().show2BtnDialog(new CpComDialog.Dialog2BtnCallBack() {
            @Override
            public void sure() {
                if (callBack != null) {
                    callBack.needCheck(noShowPermissions);
                }
                AppUtils.jumpAppSettingInfo(c);
            }

            @Override
            public void cancel() {
                if (callBack != null) {
                    callBack.denied(noShowPermissions);
                }
            }
        });
        TimeUtils.isCheckFastClick = true;
    }

    public UniPersUtil setShowGuideDialog(boolean showGuideDialog) {
        isShowGuideDialog = showGuideDialog;
        return this;
    }

    public UniPersUtil setHandleResult(boolean handleResult) {
        isHandleResult = handleResult;
        return this;
    }

    public UniPersUtil setGuideDialogMsg(String guideDialogMsg) {
        this.guideDialogMsg = guideDialogMsg;
        return this;
    }

    public UniPersUtil setCallBack( GrantedCallBack callBack) {
        this.callBack = callBack;
        return this;
    }

    public interface GrantedCallBack {
        void granted(Object source, int requestCode);//全部允许
        void denied(List<String> deniedPermissions);//点击引导弹框的拒绝按钮
        void needCheck(List<String> deniedPermissions);//需要继续检测权限情况：点击引导弹框的设置按钮、或点击权限不允许按钮
        void deniedNoShow(List<String> deniedPermissions);
    }
    /**
     * 给被拒绝的权限分组：1、询问 2、禁止询问
     * deniedPermissions：被拒绝过的权限
     */
    @TargetApi(value = Build.VERSION_CODES.M)
    public static Map<String, List<String>> groupDeniedPermissions(Activity activity, List<String> deniedPermissions){
        Map<String, List<String>> group = new HashMap<>();
        List<String> psShow = new ArrayList<>();//被拒绝并且允许询问的权限
        List<String> psNoShow = new ArrayList<>();//被拒绝并且禁止询问的权限
        for(String value : deniedPermissions){
            if(ActivityCompat.shouldShowRequestPermissionRationale(activity,value)){
                psShow.add(value);
            }else{
                psNoShow.add(value);
            }
        }
        group.put("show",psShow);
        group.put("noShow",psNoShow);
        LogUtil.i("","group="+group);
        return group;
    }
}
